package com.ifcar.app.data.dao.impl;

import com.ifcar.app.data.dao.AccountData;
import com.ifcar.app.db.DBUtil;
import com.ifcar.app.util.Dict;
import com.ifcar.app.util.StringUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;

/**
 * 数据层实现
 * @author nxlixa
 *
 */
public class AccountDataImpl implements AccountData{
	
	private DB mDb;
	
	public AccountDataImpl(){
		mDb = DBUtil.mDb;
		if(null == mDb){
			// TODO ..
			System.err.println("db init error");
		}
		
	}
	
	// 通过邮箱账号查找用户
	@Override
	public DBCursor findUserObjByEmail(String email) {
		
		DBCollection userColl = mDb.getCollection(DBUtil.COLLECTION_USERS_BASE);
		
		DBObject obj = new BasicDBObject();
		obj.put(Dict.EMAIL, email);
		
		DBCursor cursor = userColl.find(obj);
		
		return cursor;
	}

	// 通过电话号码查找用户
	@Override
	public DBCursor findUserObjByPhone(String phone) {
		
		DBCollection userColl = mDb.getCollection(DBUtil.COLLECTION_USERS_BASE);
		
		DBObject obj = new BasicDBObject();
		obj.put(Dict.PHONENUM, phone);
		
		DBCursor cursor = userColl.find(obj);
		
		return cursor;
	}

	// 用户注册
	@Override
	public WriteResult register(String phone, String pwd, String email) {
		
		DBCollection userBaseColl = mDb.getCollection(DBUtil.COLLECTION_USERS_BASE);
		DBObject userObj = new BasicDBObject();

		if(!StringUtil.isEmptyStr(phone)){
			userObj.put(Dict.PHONENUM, phone);
		}
		
		if(!StringUtil.isEmptyStr(pwd)){
			userObj.put(Dict.PWD, StringUtil.md5Encrypt(pwd));
		}
		
		if(!StringUtil.isEmptyStr(email)){
			userObj.put(Dict.EMAIL, email);
		}
		
		WriteResult wr = userBaseColl.save(userObj);
		
		return wr;
	}

	@Override
	public DBCursor findUserObj4Login(String phone, String pwd) {
		
		DBCollection userColl = mDb.getCollection(DBUtil.COLLECTION_USERS_BASE);
		
		DBObject obj = new BasicDBObject();
		obj.put(Dict.PHONENUM, phone);
		obj.put(Dict.PWD, StringUtil.md5Encrypt(pwd));
		
		DBCursor cursor = userColl.find(obj);
		return cursor;
	}
	

}
